package com.valveinspectionsys.order.activity;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONException;
import org.json.JSONObject;

import com.valveinspectionsys.R;
import com.valveinspectionsys.dbhelp.DbTableName;
import com.valveinspectionsys.dbhelp.XmlNameHelper;
import com.valveinspectionsys.httpserver.RequestUrl;
import com.valveinspectionsys.httpserver.UploadHttpClient;
import com.valveinspectionsys.order.db.OrderDao;
import com.valveinspectionsys.povo.EngineeringOrderPoVo;
import com.valveinspectionsys.povo.ImagePoVo;
import com.valveinspectionsys.util.FileNameUtil;
import com.valveinspectionsys.util.SharedPreferenceUtil;


import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

public class ReportUploadActivity extends Activity {
    


    public Button button;// 上传按钮

    public TextView textview1;// 需上传总数

    public TextView textview2;// 未上传总数

    public TextView textview3;// 进度条描述

    public ProgressBar pb;// 进度条

    public OrderDao dao;

    public TextView textview4;

    public List<EngineeringOrderPoVo> list;

    public boolean isstop = false;

    public int total = 0;
    public SharedPreferenceUtil sp;
    
    public RequestUrl r;

 
    @Override
    protected void onCreate(Bundle savedInstanceState) {

	super.onCreate(savedInstanceState);
	setContentView(R.layout.waterbanding_onetoupload);
	sp=new SharedPreferenceUtil(this);
	dao=new OrderDao(this, sp.getValue(XmlNameHelper.SqliteName));
	init();
	
	
	r=new RequestUrl(this);
    }

    /**
     * 初始化控件
     */
    public void init() {
	button = (Button) findViewById(R.id.waterbanding_upload_button);
	pb = (ProgressBar) findViewById(R.id.waterbanding_progressBar);
	textview1 = (TextView) findViewById(R.id.waterbanding_upload_total);
	textview2 = (TextView) findViewById(R.id.waterbanding_noupload_total);
	textview3 = (TextView) findViewById(R.id.waterbanding_pb_textview);
	textview4 = (TextView) findViewById(R.id.onekeyupload_info);
	textview4.setText("工程单一键上传");
	
	textview1.setText(dao.queryOrderTotal() + "");
	textview2.setText(dao.queryOrderUpload() + "");
	this.list = dao.queryUpload(null);
	
	button.setOnClickListener(new OnClickListener() {

	    @Override
	    public void onClick(View v) {

		if (list == null || list.size() < 1) {
		    Toast.makeText(ReportUploadActivity.this, "没有可上传的数据!", Toast.LENGTH_LONG).show();
		    return;
		}
		
		if (dao.queryOrderUpload() <= 0) {
		    Toast.makeText(ReportUploadActivity.this, "没有上传的数据了！", 1000).show();
		    return;
		}
		list = dao.queryUpload(null);
		
		pb.setMax(list.size());
		textview3.setText("正在上传中....0%");
		new Thread() {

		    @Override
		    public void run() {

			
			SharedPreferenceUtil sh = new SharedPreferenceUtil(ReportUploadActivity.this);
			String url = r.getUrl(RequestUrl.UploadOrder);
                         System.out.println("------url------"+url);
			for (int i = 0; i < list.size(); i++) {
			    EngineeringOrderPoVo e = list.get(i);
			    Map<String, String> map3 = new HashMap<String, String>();
			    map3.put("desc", e.getDesc());
			    map3.put("typeid", e.getTypenumber());
			    map3.put("waternumber", e.getWaternumber());
			    map3.put("name", e.getName());
			    map3.put("latitude", e.getLatitude() + "");
			    map3.put("longitude", e.getLongitude() + "");

			    map3.put("imsi", sh.getValue(XmlNameHelper.IMEI));

			    List<ImagePoVo> fileparam = new ArrayList<ImagePoVo>();

			    List<String> img = e.getImagepath();

			    if (img != null && img.size() > 0) {
				for (int k = 0; k < img.size(); k++) {
				    File files = new File(img.get(k));
				    if (files.exists()) {
					ImagePoVo po = new ImagePoVo();
					po.setFile(files);
					po.setKey("imagepath");
					po.setKeyName(files.getName());
					po.setValues("imagename");
					fileparam.add(po);

				    }
				}
			    }

			    if (e.getVideopath() != null && !TextUtils.isEmpty(e.getVideopath())) {
				File videofile = new File(e.getVideopath());
				if (videofile.exists()) {
				    ImagePoVo po = new ImagePoVo();
				    po.setFile(videofile);
				    po.setKey("videopath");
				    po.setKeyName(videofile.getName());
				    po.setValues("videoname");
				    fileparam.add(po);
				}
			    }

			    if (e.getSoundpath() != null && !TextUtils.isEmpty(e.getSoundpath())) {
				File soundfile = new File(e.getSoundpath());
				if (soundfile.exists()) {
				    ImagePoVo po = new ImagePoVo();
				    po.setFile(soundfile);
				    po.setKey("soundpath");
				    po.setKeyName(soundfile.getName());
				    po.setValues("soundpath");
				    fileparam.add(po);
				}
			    }

			    String respon = UploadHttpClient.uploadSubmit(url, fileparam, map3);
			    if (respon.equals("error")) {

				Message msg = MyHandle.obtainMessage();
				msg.what = 0;
				MyHandle.sendMessage(msg);
				return;
			    } else {
				try {
				    JSONObject json = new JSONObject(respon);
				    String message = json.getString("message");
				    if (message.equals("yes")) {
					if (i == (list.size() - 1)) {
					    Message msg = MyHandle.obtainMessage();
					    msg.what = 1;
					    MyHandle.sendMessage(msg);
					    return;
					} else {

					    Message msg = MyHandle.obtainMessage();
					    msg.what = 2;
					    msg.arg1 = i + 1;
					    MyHandle.sendMessage(msg);
					}

				    } else {
					Message msg = MyHandle.obtainMessage();
					msg.what = 0;
					MyHandle.sendMessage(msg);
					return;
				    }
				} catch (JSONException e1) {
				    Message msg = MyHandle.obtainMessage();
				    msg.what = 0;
				    MyHandle.sendMessage(msg);
				    return;

				}

			    }

			}

		    }

		}.start();

	    }
	});

    }

    /**
     * 消息处理
     */
    Handler MyHandle = new Handler() {

	@Override
	public void handleMessage(Message msg) {

	    if (msg.what == 0) {
		pb.setProgress(0);
		textview3.setText("正在上传中.....0%");
		Toast.makeText(ReportUploadActivity.this, "网络连接错误！", Toast.LENGTH_LONG).show();

	    } else if (msg.what == 1) {
		pb.setProgress(list.size());
		textview3.setText("上传完毕100%");
		Toast.makeText(ReportUploadActivity.this, "上传成功！", Toast.LENGTH_LONG).show();
		
		dao.delectAll(DbTableName.ORDER);
		textview1.setText("0");
		textview2.setText("0");

		dao.close();
		FileNameUtil f = new FileNameUtil();
		f.delectFile("order");
		

	    } else if (msg.what == 2) {
		System.out.println(msg.arg1 / list.size() * 100 + "%");
		textview3.setText("正在上传中....." + ((float) msg.arg1) / list.size() * 100 + "%");
		pb.setProgress(msg.arg1);

	    }
	    super.handleMessage(msg);
	}

    };

    @Override
    protected void onDestroy() {
	if (dao != null) {
	    dao.close();
	}
	super.onDestroy();
    }

   


}
